package com.bw.gmall.realtime.dww.App;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bw.gmall.realtime.common.Util.DateFormatUtil;
import com.bw.gmall.realtime.common.base.BaseApp;
import com.bw.gmall.realtime.common.constant.Constant;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SideOutputDataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;

public class DwdBaseLog extends BaseApp {


    public static void main(String[] args) throws Exception {
        new DwdBaseLog().start(10011,4, Constant.TOPIC_LOG,Constant.TOPIC_LOG);

    }

    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) throws Exception {

        // 1.做数据清洗
        SingleOutputStreamOperator<JSONObject> flatMapStream = stream.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String s, Collector<JSONObject> collector) throws Exception {


                try {
                    JSONObject jsonObject = JSON.parseObject(s);
                    String ts = jsonObject.getString("ts");
                    JSONObject common = jsonObject.getJSONObject("common");
                    String mid = common.getString("mid");

                    if (ts != null && mid != null) {
                        collector.collect(jsonObject);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });

//        2.新用户校验

//        加水位线
        SingleOutputStreamOperator<JSONObject> waterStream = flatMapStream.assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3)).withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
            @Override
            public long extractTimestamp(JSONObject jsonObject, long l) {
                return jsonObject.getLong("ts");
            }
        }));

        SingleOutputStreamOperator<JSONObject> isNewStream = waterStream.keyBy(x -> x.getJSONObject("common").getString("mid"))
                .process(new KeyedProcessFunction<String, JSONObject, JSONObject>() {

                    ValueState<String> state;

                    @Override
                    public void open(Configuration parameters) throws Exception {

                        state = getRuntimeContext().getState(new ValueStateDescriptor<String>("state", String.class));
                    }

                    @Override
                    public void processElement(JSONObject jsonObject, KeyedProcessFunction<String, JSONObject, JSONObject>.Context context, Collector<JSONObject> collector) throws Exception {

//                        获取状态的值

                        String value = state.value();
                        Long ts = jsonObject.getLong("ts");
                        JSONObject common = jsonObject.getJSONObject("common");
                        String isNew = common.getString("is_new");

//                        当前日期
                        String curDate = DateFormatUtil.tsToDate(ts);
                        // 想想逻辑
                        // 如果是新用户
                        // 2024-08-16  10  1  10:00
                        // 2024-08-16  10  1  12:00
                        // 2024-08-17  10  0  10.00

                        if ("1".equals(isNew)) {
                            if (value == null) {
                                state.update(curDate);
                            } else if (!value.equals(curDate)) {
                                common.put("is_new", 0);
                            }
                        } else if ("0".equals(isNew)) {
                            // 认为昨天登录
                            state.update(DateFormatUtil.tsToDate(ts - 4 * 60 * 60 * 1000));
                        } else {

                        }
                        collector.collect(jsonObject);

                    }
                });


        // 分流
//      TypeInformation() 讲传入类型转成string
        OutputTag<String> startTag = new OutputTag<String>("start", TypeInformation.of(String.class)){};
        OutputTag<String> errorTag = new OutputTag<String>("err", TypeInformation.of(String.class)){};
        OutputTag<String> displayTag = new OutputTag<String>("display", TypeInformation.of(String.class)){};
        OutputTag<String> actionTag = new OutputTag<String>("action", TypeInformation.of(String.class)){};


        SingleOutputStreamOperator<String> processStream = isNewStream.process(new ProcessFunction<JSONObject, String>() {
            @Override
            public void processElement(JSONObject jsonObject, ProcessFunction<JSONObject, String>.Context context, Collector<String> collector) throws Exception {

                JSONObject err = jsonObject.getJSONObject("err");
//                错误日志
                if (err != null) {
                    context.output(errorTag, jsonObject.toJSONString());
                    jsonObject.remove("err");
                }

                JSONObject start = jsonObject.getJSONObject("start");
                JSONObject page = jsonObject.getJSONObject("page");
                JSONObject common = jsonObject.getJSONObject("common");
                Long ts = jsonObject.getLong("ts");

                if (start != null) {
                    context.output(startTag, jsonObject.toJSONString());
                } else if (page != null) {
                    JSONArray dispalys = jsonObject.getJSONArray("displays");
                    // 曝光
                    if (dispalys != null) {
                        for (int i = 0; i < dispalys.size(); i++) {
                            //{{"item":"5","item_type":"sku_id","pos_id":4,"pos_seq":0},common:{},ts:12321312,"page":{}}

                            JSONObject display = dispalys.getJSONObject(i);
                            display.put("common", common);
                            display.put("ts", ts);
                            display.put("page", page);
                            context.output(displayTag, display.toJSONString());

                        }
                        dispalys.remove("displays");
                    }
                }

                // 动作
                JSONArray acitons = jsonObject.getJSONArray("acitons");
                if (acitons != null) {
                    for (int i = 0; i < acitons.size(); i++) {
                        //{{"item":"5","item_type":"sku_id","pos_id":4,"pos_seq":0},common:{},ts:12321312,"page":{}}

                        JSONObject action = acitons.getJSONObject(i);
                        action.put("common", common);
                        action.put("ts", ts);
                        action.put("page", page);
                        context.output(actionTag, action.toJSONString());

                    }
                    acitons.remove("actions");
                }

                collector.collect(jsonObject.toJSONString());
            }
        });


        // 取出侧流
        SideOutputDataStream<String> startStream = processStream.getSideOutput(startTag);
        SideOutputDataStream<String> errorStream = processStream.getSideOutput(errorTag);
        SideOutputDataStream<String> displayStream = processStream.getSideOutput(displayTag);
        SideOutputDataStream<String> actionStream = processStream.getSideOutput(actionTag);


        // 6、寫到kakfa
        startStream.print("start------------");
        errorStream.print("error---------");
        displayStream.print("display--------");
        actionStream.print("actionStream--------");
        processStream.print("processStream--------");

    }
}
